##

rm(list = ls())

## 

library(tidyverse)
library(knitr)
library(kableExtra)

## Load saved results

res_df_rdd_muni <- read_rds('data/rdd_municipal_results.rds') %>% 
  mutate(unit = 'Municipal election') %>% 
  filter(!str_detect(outcome, "agg|total"))

res_df_rdd_bundestag <- read_rds('data/rdd_federal_results.rds') %>% 
  mutate(unit = 'Federal election') %>% 
  mutate(outcome = str_remove(outcome, "_party")) %>% 
  filter(!str_detect(outcome, "agg|total"))

res_df_rdd_landtag <- read_rds('data/rdd_state_results.rds') %>% 
  mutate(unit = 'State election') %>% 
  filter(!str_detect(outcome, "agg|total"))

## Combine

results_rdd <- bind_rows(res_df_rdd_muni, 
                         res_df_rdd_bundestag,
                         res_df_rdd_landtag) %>% 
  filter(!str_detect(outcome, "incumbent"))

## Some renaming

results_rdd <- results_rdd %>%
  mutate(outcome2 = dplyr::recode(outcome, 
                                 `turnout` = 'Turnout',
                                 `cdu_csu` = 'CDU/CSU',
                                 `spd` = 'SPD',
                                 `left` = 'Left party',
                                 `greens` = 'Greens',
                                 `fdp` = 'FDP',
                                 `afd` = 'AfD',
                                 `other` = 'Other',
                                 `other_party` = 'Other',
                                 `wahlerver_total` = 'Other')) %>% 
  mutate(unit = dplyr::recode(unit, 
                              `Bundestag` = 'Federal election',
                              `Landtag` = 'State election',
                              `Municipal council` = 'Municipal election')) %>% 
  mutate(unit = factor(unit, levels = c('Federal election',
                                        'State election',
                                        'Municipal election'))) %>% 
  mutate(outcome2 = factor(outcome2, 
                          levels = c('AfD', 'FDP', 'CDU/CSU', 'SPD', 
                                     'Greens', 'Left party', 'Other',
                                     'Turnout'))) %>% 
  mutate(exclude_state = ifelse(exclude_state == 'All states',
                                'Full sample', 'B-W excluded'))

## Drop aggregate outcomes

results_rdd_allparties <- results_rdd %>%
  filter(!outcome2 %in% c('Left parties', 'Right parties'))

## Prepare for returning as table

turn_df <- results_rdd_allparties %>% 
  mutate_at(vars(estimate, 
                 matches('conf'), 
                 pval), list(~round(., 2))) %>% 
  mutate(ci = paste0('[',conf.low, ', ',conf.high, ']')) %>% 
  dplyr::select(unit, outcome2, exclude_state, estimate, 
                ci, pval, bw, bw_bias, n, unit) %>%
  mutate(bw = round(bw, 0), bw_bias = round(bw_bias, 0)) %>% 
  arrange(unit, outcome2) %>% 
  dplyr::select(-unit)

# Table A.6: Results by party ----

kable(turn_df, "latex", longtable = F, 
      booktabs = T, col.names = c('Outcome',
                                  'Sample', '$\\hat{\\tau}_{\\text{SRD}}$',
                                  '95\\% CI', 'P-val',
                                  '$h_{\\text{MSE}}$',
                                  '$b_{\\text{MSE}}$',
                                  '$n$'),
      linesep = "",
      caption = 'RDD Results for three elections, by party\\label{tab:main_appendix_allparties}',
      escape = F) %>%
  kable_styling(latex_options = c("repeat_header"),
                font_size = 10) %>% 
  # collapse_rows() %>% 
  row_spec(0, bold = T) %>% 
  kable_styling(latex_options = "HOLD_position", ) %>% 
  pack_rows(start_row = 1, end_row = 16, group_label = 'Federal elections') %>% 
  pack_rows(start_row = 17, end_row = 32, group_label = 'State elections') %>% 
  pack_rows(start_row = 33, end_row = 46, group_label = 'Municipal elections') 
